<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/Epi/Epi.php';
include_once $_SERVER['DOCUMENT_ROOT'].API::$dbConf;;
Epi::init('database');
EpiDatabase::employ('mysql', $db_prm['db'], $db_prm['server'], $db_prm['usn'], $db_prm['pwd']);
if(!empty($db_prm['set_names'])){
	try{
    \getDatabase()->execute("SET NAMES '".$db_prm['set_names']."'");
	}catch(Exception $e){
	  throw_error('DB set location:'.$e->getMessage(),500);
	}
}

class UserModel{
	protected static $_instance;

	private function __construct(){}
	private function __clone(){}
	public static function inst(){
	  if( null===self::$_instance ){
	    self::$_instance=new self();
		}
		return self::$_instance;
	}

	protected $errors=array('err'=>array(),'wrn'=>array());
	protected function error($msg){ $this->errors['err'][]=$msg; return false;}
	protected function warning($msg){ $this->errors['wrn'][]=$msg; return false;}
	public function getError(){ return $this->errors['err'][ count($this->errors['err'])-1 ]; }
	public function getErrors(){ return $this->errors['err']; }
	public function getWarning(){ return $this->errors['wrn'][ count($this->errors['wrn'])-1 ]; }
	public function getWarnings(){ return $this->errors['wrn']; }

	public function getData($sql,$params=array(),$one=false,$retErr=false){
	  //Доставляю язык, если ннада
	  if( strpos($sql, ':ln')!=false && empty($params[':ln']) )	$params[':ln']=Api::$lang;
	  try{
	    if($one)
	      $rs=\getDatabase()->one($sql,$params);
	    else
	    	$rs=\getDatabase()->all($sql,$params);
		}catch(Exception $e){
		  throw_error('get data: '.$e->getMessage(),500);
		}
		
    if(empty($rs)) return $this->error('Result empty',$retErr);
	  return $rs;
	}
	
	protected function checkAuth($retErr=false){
	  if( empty($_GET['token']) ) return false;
	  if( $_GET['token']==getSysToken() ) return true;
	  
		$rs=$this->checkToken($_GET['token'],$retErr);

	  if(empty($rs['t_key_user']))
			if(!empty($rs->error)) throw_error('Auth '.$rs->error);
			else return false;
	  return true;
	}

	public function getUser($id=false,$retErr=false){
	  if( empty($id) ) throw_error('get user: ID expected',400);
	  if(!$this->checkAuth()) throw_error('Auth expected',400);
	  if( substr($id, 0, 2)=='ur' )
			$where=' u_id=:id';
		else
			$where=' u_url=:id';
		$sql="SELECT	u_id,u_type,u_name,u_nameShort,u_createtime,u_email
					FROM		user
					WHERE		$where";

	  $rs=$this->getData(
			$sql,
			array(':id'=>$id),
			true,
			$retErr
		);
		return $rs;
	}
	
	public function getUserByToken($id=false,$retErr=false){
	  if( empty($id) ) throw_error('token: ID expected',400);
	  if( substr($id, 0, 2)!='tn' )	throw_error('token: only token ID expected',400);

	  return $this->getData(
			"SELECT	u_id,u_type,u_name,u_nameShort,u_createtime,u_email
			FROM		user,token
			WHERE		t_id=:id AND t_dead > :now AND u_id=t_key_user",
			array(':id'=>$id, ':now'=>mktime()),
			true,
			$retErr
		);
	}
	
	public function getUserByEmail($id=false,$retErr=false){
	  if( empty($id) ) throw_error('byEmail: email expected',400);
	  if( !preg_match('/^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$/i', $id) )
			throw_error('byEmail: only email expected',400);
		$sql="SELECT	u_id,u_type,u_name,u_nameShort,u_createtime,u_email
					FROM		user LEFT JOIN user_soc ON(u_id=us_key_user)
					WHERE		us_email=:id OR u_email=:id";
	  return $this->getData(
			$sql,
			array(':id'=>$id),
			true
		);
	}
	
	public function checkToken($id=false,$retErr=false){
	  if( empty($id) ) throw_error('token: ID expected',401 );
	  if( substr($id, 0, 2)!='tn' )	throw_error('token: only token ID expected',401 );
	  $rs=$this->getData(
			"SELECT	t_id,t_key_user,t_dead
			FROM		token
			WHERE		t_id=:id",
			array(':id'=>$id),
   		true
		);
		
		if(empty( $rs )) throw_error('token not found',404);
		elseif($rs['t_dead'] <= mktime()) throw_error('token expired',404);
		return $rs;
	}

	
	public function getUsersByGeo($id,$retErr=false){
	  if( empty($id) ) throw_error('user by geo: ID expected',400);
	  if(!User::maskID($id,'country|region|city|urban')) throw_error('user by geo: expected ID of country,region,city or urbanarea',400);
	  //Получение GET параметров
	  $limit=20;
	  if($prm['page']=='all') $limit=100;
   	$page=intval($prm['page']); if(empty($page))$page=1;
    $page--;

		$sql="SELECT DISTINCT u_id,u_type,u_name,u_name,u_nameShort
			 FROM user,user2geo
			 WHERE u2g_key_user=u_id AND u2g_key_geo=:id";
			 
		$sql_prm=array( ':id'=>$id );
			 
		$sql.=' LIMIT :from,:limit';
		$sql_prm[':from']	=array(	($page*$limit),PDO::PARAM_INT	);
		$sql_prm[':limit']=array(	$limit,PDO::PARAM_INT	);
	  return $this->getData($sql,$sql_prm);
	}
}
?>